<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:include="include :: header"></head>
<body class="hold-transition skin-blue sidebar-mini">
<!--导入模态框-->
<div class="modal fade" data-backdrop="static" data-keyboard="false" id="modal-import">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Excel信息导入</h4>
            </div>
            <div class="modal-body">
                <form id="importForm">
                    <div class="form-group">
                        <label>模版</label>
                        <a class="card" th:href="@{/file/工艺卡模板.xlsx}">点击下载</a>
                    </div>
                    <div class="form-group">
                        <label>选择Excel文件并上传</label>
                        <input id="import-file" class="btn" type="file" name="file">
                        <p class="help-block">请按模板格式进行导入，信息与模板信息对应。</p>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="btn-import" type="button" class="btn btn-success">
                    <span class="Bold">确定</span>
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<section class="content">
    <div class="row" style="margin-bottom: 24px">
        <!--<div class="col-xs-11 col-xs-offset-1">-->
            <span style="font-size: 24px" id="h3-drawNo"></span>&emsp;&emsp;
            <span style="font-size: 24px" id="h3-drawName"></span>
            <a id="btn-save" shiro:hasPermission="est:add:edit" href="javascript:void(0);"
               class="btn btn-info pull-right" style="margin-right: 10px">
                <span class="Bold">确定</span>
            </a>
            <a shiro:hasPermission="est:add:edit" href="javascript:void(0);"
           class="btn btn-success pull-right" style="margin-right: 10px"
           onclick="js.modal.open('modal-import')">
            <span class="Bold">导入</span>
            </a>
    </div>
    <div class="row">
        <form id="cardForm" class="form-horizontal">
            <div class="col-xs-11 col-xs-offset-1">
                <table class="t1 t3">
                    <thead>
                    <tr>
                        <td colspan="10">
                            <img th:src="@{/img/logo3.jpg}" width="64px" height="40px" style="margin-top: -20px">
                            <div style="display: inline-block;margin-top: 5px;margin-left: 20px">
                                <span style="letter-spacing: 24px;display: block;line-height: 20px">&nbsp;辽宁忠旺机械设备制造有限公司</span>
                                <span style="display: block;font-size: 12px;line-height: 20px">Liaoning Zhongwang Machinery Equipment Manufacturing Co., Ltd</span>
                            </div>
                        </td>
                        <td colspan="2">工艺过程卡</td>
                        <td style="width: 9%"></td>
                    </tr>
                    <tr>
                        <td style="width: 8%">项目编号</td>
                        <td colspan="2" style="width: 11%;font-size: 14px;">
                            <select id="proCode" class="form-control" name="proCode"></select>
                        </td>
                        <td style="width: 8%">项目名称</td>
                        <td colspan="2" style="width: 16%">
                            <input id="proName" type="text" class="form-control" name="proName" readonly>
                        </td>
                        <td style="width: 8%">项目数量</td>
                        <td style="width: 8%">
                            <input id="proNum" type="number" class="form-control" name="proNum" readonly>
                            <input type="hidden" id="proUnit" name="proUnit">
                        </td>
                        <td style="width: 8%">类型</td>
                        <td style="width: 8%">
                            <select id="special" class="form-control" name="special">
                                <option value="">请选择</option>
                                <option th:each="s : ${specials}" th:value="${s.name}"
                                        th:text="${s.name}"></option>
                            </select>
                        </td>
                        <td style="width: 8%">部分</td>
                        <td style="width: 8%">
                            <select id="part" class="form-control" name="partId">
                                <option value="">请选择</option>
                            </select>
                        </td>
                        <td></td>
                    </tr>
                    <tr>
                        <td rowspan="2">零件图号</td>
                        <td rowspan="2" colspan="3">
                            <select id="craMakeDetailId" class="form-control select2" name="craMakeDetailId">
                                <option value="">请选择</option>
                            </select>
                            <input id="drawNo" type="hidden" name="drawNo">
                        </td>
                        <td rowspan="2" style="width: 8%">零件名称</td>
                        <td rowspan="2"><input id="drawName" type="text" class="form-control" name="drawName" readonly></td>
                        <td>零件数量</td>
                        <td><input id="drawNum" type="number" step="0.1" class="form-control" name="drawNum" readonly></td>
                        <td>材质</td>
                        <td><input id="quality" type="text" class="form-control" name="quality" autocomplete="off"></td>
                        <td>重量(kg)</td>
                        <td><input id="weight" type="number" step="0.1" class="form-control" name="weight"></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>规格</td>
                        <td colspan="5"><input id="spec" type="text" class="form-control" name="spec" autocomplete="off"></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>路线</td>
                        <td style="width: 5%">序号</td>
                        <td style="width: 6%">工序</td>
                        <td>设备名称</td>
                        <td colspan="8">工艺内容</td>
                        <td></td>
                    </tr>
                    </thead>
                    <tbody id="card">
                    <tr>
                        <td>
                            <select class="form-control" name="route" title="">
                                <option th:each="r : ${routes}" th:value="${r.name}"
                                        th:text="${r.name}"></option>
                            </select>
                        </td>
                        <td>
                            <input type="text" class="form-control" name="orderNo" autocomplete="off">
                        </td>
                        <td>
                            <select id="select-process"   class="form-control" name="process" title=""  onchange="additional1()">
                                <option th:each="p : ${processes}" th:value="${p.name}"
                                        th:text="${p.name}"></option>
                            </select>
                        </td>
                        <td>
                            <select id="selectEquName" class="form-control" name="equName" title="">
                                <option value=""></option>
                                <!--<option th:each="e : ${equNames}" th:value="${e.name}"-->
                                        <!--th:text="${e.name}"></option>-->
                            </select>
                        </td>
                        <td colspan="8">
                            <textarea class="form-control" name="craftContent" rows="1"></textarea>
                            <!--<input type="text" class="form-control" name="craftContent" autocomplete="off">-->
                        </td>
                        <td style="font-size: 16px;">
                            <span class="card-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                            <span class="card-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <select class="form-control" name="route" title="">
                                <option th:each="r : ${routes}" th:value="${r.name}"
                                        th:text="${r.name}" th:selected="${r.name=='转储'}"></option>
                            </select>
                        </td>
                        <td>
                            <input type="text" class="form-control" name="orderNo" autocomplete="off">
                        </td>
                        <td>
                            <select class="form-control" name="process" title="">
                                <option th:each="p : ${processes}" th:value="${p.name}"
                                        th:text="${p.name}" th:selected="${p.name=='制作完成'}"></option>
                            </select>
                        </td>
                        <td>
                            <select class="form-control" name="equName" title="">
                                <option value=""></option>
                                <option th:each="e : ${equNames}" th:value="${e.name}"
                                        th:text="${e.name}"></option>
                            </select>
                        </td>
                        <td colspan="8">
                            <textarea class="form-control" name="craftContent" rows="1">制作完成</textarea>
                            <!--<input type="text" class="form-control" name="craftContent" autocomplete="off">-->
                        </td>
                        <td style="font-size: 16px;">
                            <span class="card-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                            <span class="card-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                        </td>
                    </tr>
                    </tbody>
                    <tfoot>
                    <tr>
                        <td>编制人员</td>
                        <td colspan="2">
                            <input type="text" class="form-control" name="createName" th:value="${session.user.name}" readonly>
                        </td>
                        <td>联系电话</td>
                        <td colspan="2">
                            <input type="text" class="form-control" name="createTel" th:value="${session.user.tel}" autocomplete="off">
                        </td>
                        <td>审核人员</td>
                        <td colspan="2">
                            <select id="verifyCode" class="form-control" name="verifyCode" title="">
                                <option value="">请选择</option>
                                <option th:each="v : ${verifys}" th:value="${v.code}"
                                        th:text="${v.name}"></option>
                            </select>
                            <input id="verifyName" type="hidden" name="verifyName">
                        </td>
                        <td>审核时间</td>
                        <td colspan="2">
                            <!--<input type="text" class="form-control" name="verifyTime" autocomplete="off">-->
                        </td>
                        <td></td>
                    </tr>
                    <!--<tr>
                        <td>定额人员</td>
                        <td colspan="2">
                            &lt;!&ndash;<input type="text" class="form-control" name="quotaName" autocomplete="off">&ndash;&gt;
                        </td>
                        <td>下达日期</td>
                        <td colspan="2">
                            &lt;!&ndash;<input type="text" class="form-control" name="notifyTime" autocomplete="off">&ndash;&gt;
                        </td>
                        <td>修改人员</td>
                        <td colspan="2">
                            &lt;!&ndash;<input type="text" class="form-control" name="updateName" autocomplete="off">&ndash;&gt;
                        </td>
                        <td>修改日期</td>
                        <td colspan="2">
                            &lt;!&ndash;<input type="text" class="form-control" name="updateTime" autocomplete="off">&ndash;&gt;
                        </td>
                        <td></td>
                    </tr>-->
                    </tfoot>
                </table>
            </div>
        </form>
    </div>
</section>
<div id="div-route" style="display: none">
    <select class="form-control" name="route" title="">
        <option th:each="r : ${routes}" th:value="${r.name}"
                th:text="${r.name}"></option>
    </select>
</div>
<div id="div-process" style="display: none">
    <select  class="form-control" name="process" title="">
        <option th:each="p : ${processes}" th:value="${p.name}"
                th:text="${p.name}"></option>
    </select>
</div>
<div id="div-equName" style="display: none">
    <select class="form-control" name="equName" title="">
        <option value=""></option>
        <option th:each="e : ${equNames}" th:value="${e.name}"
                th:text="${e.name}"></option>
    </select>
</div>
<div th:include="include :: footer"></div>
<script th:src="@{/plugin/SheetJs/xlsx.core.min.js}"></script>
<script th:inline="javascript">
    let dynamicId=0;
    /** 获取工序下拉列表*/
    function drawNoSelect() {
        js.post({
            url: ctx + "est/add/processList/",
            success: function (result) {
                let resultList = result.data.rows;
                if (result.data.total > 0) {
                    sessionStorage.setItem("proessNoList", JSON.stringify(resultList));
                }
            }
        })
    }
    /** 在固定的td里面填充select*/
    function additional() {
        var reasonArry = JSON.parse(sessionStorage.getItem("proessNoList"));
        $("#selectDarwNoList"+dynamicId).append(`<option value="">请选择</option>`);
        if (reasonArry == null) {
            return;
        }
        reasonArry.forEach(value => {
            if (value) {
                $("#selectDarwNoList" + dynamicId).append(`<option  value="${value.name}">${value.name}</option>`);
            }
        })
    }
    /** 首次工序改变事件*/
    function additional1() {
        var valuez = $('#select-process').val();
        js.post({
            url: ctx + 'est/add/selectBuf',
            data: {
                name : valuez
            },
            success: function (result) {
                $("#selectEquName").empty().append(`<option value=""></option>`);
                result.data.rows.forEach(value => {
                    if (value) {
                        $("#selectEquName").append(`<option value="${value.name}">${value.name}</option>`);
                    }
                })
            }
        })

    }
    /** 工序改变事件*/
    function selectDrawName(dom) {
        var idii= dom.id;
        var num = idii.substring(16);
        var valuez = $(dom).find('option:selected').val();
        js.post({
            url: ctx + 'est/add/selectBuf',
            data: {
                name : valuez
            },
            success: function (result) {
                $("#selectEquName"+num).empty().append(`<option value=""></option>`);
                result.data.rows.forEach(value => {
                    if (value) {
                        $("#selectEquName"+num).append(`<option value="${value.name}">${value.name}</option>`);
                    }
                })
            }
        })

    }
    /** 清空零件信息 */
    function emptyComp() {
        $("#DrawNo").val('');
        $("#drawName").val('');
        $("#drawNum").val('');
        $("#quality").val('');
        $("#spec").val('');
        $("#weight").val('');
    }

    /** 获取部分 */
    function getPart() {
        let code = $("#proCode").val();
        let type = $("#special").val();
        switch (type) {
            case '机械' :
            case '流体' :
            case '自动化' :
                fetchPart(code, type);
                break;
            case '外观' :
                fetchPart(code, null);
                break;
            case '维修备件' :
            case '设备工具' :
            case '消耗品' :
                $("#part").empty().append(`<option value="整体">整体</option>`);
                break;
            case '':
                $("#part").empty().append(`<option value="">请选择</option>`);
                break;
        }
    }
    function fetchPart(code, type) {
        js.get({
            url: ctx + 'est/add/part/list',
            data: {
                code : code,
                type : type
            },
            success: function (result) {
                $("#part").empty().append(`<option value="">请选择</option>`);
                result.forEach(value => {
                    if (value) {
                        $("#part").append(`<option value="${value.id}">${value.special}-${value.proPart}</option>`);
                    }
                })
            }
        })
    }

    /** 清空所有行并添加一行默认值 */
    function init(routeHtml, processHtml, equNameHtml) {
        $("#card").empty().append(`
                           <tr>
                                <td>
                                    ${routeHtml}
                                </td>
                                <td>
                                    <input type="text" class="form-control" name="orderNo" autocomplete="off">
                                </td>
                                <td>
                                    ${processHtml}
                                </td>
                                <td>
                                    ${equNameHtml}
                                </td>
                                <td colspan="8">
                                    <textarea class="form-control" name="craftContent" rows="1"></textarea>
                                </td>
                                <td style="font-size: 16px;">
                                    <span class="card-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                    <span class="card-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                </td>
                            </tr>
                        `)
    }

    $(function () {
        drawNoSelect();
        let routeHtml = $("#div-route").html();
        let processHtml = $("#div-process").html();
        let equNameHtml = $("#div-equName").html();

        /** 项目编号下拉框 */
        js.select2({
            id: 'proCode',
            placeholder:'',
            ajax: {
                url: function(){
                    return ctx + 'est/add/project/list'
                },
                processResults: function (data, page) {
                    let array = data;
                    for (let i = 0; i < data.length; i++) {
                        array[i]["id"] = array[i]['code'];
                        array[i]["text"] = array[i]['code'];
                    }
                    return { results: array };
                },
            }
        });
        /** 项目编号下拉框选中 */
        $("#proCode").on("select2:select",function(){
            emptyComp();
            $("#proName").val($(this).select2("data")[0].name);
            $("#proNum").val($(this).select2("data")[0].num);
            $("#proUnit").val($(this).select2("data")[0].unit);
            getPart();
        });

        $("#special").change(function () {
            getPart();
        })

        /** 部分下拉框选中 */
        $("#part").change(function () {
            emptyComp();
            let $this = $(this);
            js.get({
                url: ctx + 'est/add/drawNo/list',
                data: {
                    code : $("#proCode").val(),
                    partId : $this.val()
                },
                success: function (result) {
                    $("#craMakeDetailId").empty().append(`<option value="">请选择</option>`);
                    result.forEach(value => {
                        if (value) {
                            $("#craMakeDetailId").append(`<option value="${value.id}">${value.drawNo}</option>`);
                        }
                    });
                }
            })
        })
        /** 选择审核人 */
        $("#verifyCode").change(function () {
            $("#verifyName").val($(this).find('option:selected').text())
        })
        /** 图号下拉框选中 */
        $("#craMakeDetailId").on("select2:select",function(){
            let $this = $(this);
            if ($this.val()) {
                js.get({
                    url: ctx + 'est/add/drawNo',
                    data: {
                        id: $this.val()
                    },
                    success: function (result) {
                        $("#drawNo").val(result.drawNo);
                        $("#h3-drawNo").text(result.drawNo);
                        $("#h3-drawName").text(result.drawName);
                        $("#drawName").val(result.drawName);
                        $("#drawNum").val(result.drawNum);
                        $("#quality").val(result.quality);
                        $("#spec").val(result.specification);
                        $("#weight").val(result.weight);
                    }
                });
            } else {
                emptyComp();
                $("#h3-drawNo").text('');
            }
        });

        /** 添加一行 */
        $("#cardForm").on('click', '.card-add', function () {
            dynamicId++;
            $(this).parents("tr").after(`
                    <tr>
                        <td>
                            ${routeHtml}
                        </td>
                        <td>
                            <input type="text" class="form-control" name="orderNo" autocomplete="off">
                        </td>
                        <td>
                         <select   class="form-control" name="process" title=""
                         id="selectDarwNoList` + dynamicId + `" onchange="selectDrawName(this);" >
                            </select>

                        </td>
                        <td>
                            <select class="form-control" name="equName" title=""
                             id="selectEquName` + dynamicId + `" >
                             <option value=""></option>
                            </select>

                        </td>
                        <td colspan="8">
                            <textarea class="form-control" name="craftContent" rows="1"></textarea>
                        </td>
                        <td style="font-size: 16px;">
                            <span class="card-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                            <span class="card-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                        </td>
                    </tr>
            `);
            additional();
            $(this).parents("tr").next().find("select[name=route]").val($(this).parents("tr").find("select[name=route]").val());
            $(this).parents("tr").next().find("input[name=orderNo]").val($(this).parents("tr").find("input[name=orderNo]").val());

        });

        /** 导入 */
        $('#btn-import').click(function() {

            let files = $("#import-file")[0].files;
            // let files = e.target.files;
            let fileReader = new FileReader();
            fileReader.onload = function(ev) {
                try {
                    let data = ev.target.result,
                        workbook = XLSX.read(data, {type: 'binary'}), // 以二进制流方式读取得到整份excel表格对象
                        plans = []; // 存储获取到的数据
                    // 遍历每张表读取
                    for (let sheet in workbook.Sheets) {
                        if (workbook.Sheets.hasOwnProperty(sheet)) {
                            plans = plans.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                            break; // 只取第一张表
                        }
                    }
                    if (plans.length === 0) {
                        js.modal.alert("无法读取文件内容");
                    } else {
                        $("#card").empty();
                        plans.forEach((value, index) => {
                            $("#card").append(`
                                <tr>
                                    <td>
                                        ${routeHtml}
                                    </td>
                                    <td>
                                        <input type="text" class="form-control" name="orderNo" value="${value['序号']}" autocomplete="off">
                                    </td>
                                    <td>
                                        ${processHtml}
                                    </td>
                                    <td>
                                        ${equNameHtml}
                                    </td>
                                    <td colspan="8">
                                        <textarea class="form-control" name="craftContent" rows="1">${value['工艺内容']}</textarea>
                                    </td>
                                    <td>
                                        <span class="card-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                        <span class="card-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                    </td>
                                </tr>
                            `);
                            $("#card").find("select[name=route]:last").val(value['路线']);
                            $("#card").find("select[name=process]:last").val(value['工序']);
                            $("#card").find("select[name=equName]:last").val(value['设备名称']);
                        });
                        js.modal.hide("modal-import");
                    }
                } catch (e) {
                    js.modal.alert("无法读取文件或文件类型有错误");
                }
            };
            // 以二进制方式打开文件
            fileReader.readAsBinaryString(files[0]);
        });

        /** 删除行 */
        $('#cardForm').on('click', '.card-del', function () {
            $(this).parents("tr").remove();
            if ($("table tbody tr").length === 0) {
                $("#card").append(`
                               <tr>
                                    <td>
                                        ${routeHtml}
                                    </td>
                                    <td>
                                        <input type="text" class="form-control" name="orderNo" autocomplete="off">
                                    </td>
                                    <td>
                                        ${processHtml}
                                    </td>
                                    <td>
                                        ${equNameHtml}
                                    </td>
                                    <td colspan="8">
                                        <textarea class="form-control" name="craftContent" rows="1"></textarea>
                                    </td>
                                    <td style="font-size: 16px;">
                                        <span class="card-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                        <span class="card-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                    </td>
                                </tr>
                            `)
            }
        });

        /** 保存工艺卡 */
        $("#btn-save").click(function () {
            let $this = $(this);
            let res = js.vd({
                id: 'cardForm',
                notEmpty: ['proCode', 'proName', 'proNum', 'malType', 'partId', 'special',
                    'craMakeDetailId', 'drawName', 'drawNum', 'quality', 'weight', 'route',
                    'orderNo', 'process', 'craftContent', 'createTel', 'verifyCode']
            })
            if (!res) {
                return;
            }
            $this.attr('disabled', true);
            js.submit({
                formId: "cardForm",
                url: ctx + 'est/add/save',
                data: new FormData($("#cardForm")[0]),
                success: function (result) {
                    if (result.type === web_status.SUCCESS) {
                        // location.href = ctx + "est/cardList";
                        $("#part").trigger('change');
                        init(routeHtml, processHtml, equNameHtml);

                    } else {
                        js.modal.warning(result.msg);
                    }
                }
            });
            $this.removeAttr('disabled');
        });

    });
</script>
</body>
</html>
